import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.BorderFactory;
import TJavaLib.TList;
import TJavaLib.TString;
import net.miginfocom.swing.MigLayout;

public class TControlView extends TView {
	private TNetwork network;
	
	public JTextField txtDepArea = new JTextField(7);
	public JTextField txtSenRange = new JTextField(7);
	public JTextField txtCommRange = new JTextField(7);
	private JButton btApply = new JButton("Apply changes");
	
	public TControlView(TNetwork network, String Title) {
		super(TView.CONTROL, Title);
		frame.setPreferredSize(new Dimension(300, 200));
		frame.setClosable(false);
		this.network = network;
		
		JPanel container = new JPanel();
		container.setLayout(new MigLayout("", "[grow]"));
		add(container);
		
		JPanel pnSim = new JPanel();
		JPanel pnNet = new JPanel();
		pnNet.setLayout(new MigLayout("", "[grow]"));
		pnNet.setBorder(BorderFactory.createTitledBorder("Network preferences:"));
		pnNet.add(new JLabel("Dep. area (W x H) (m): "));
		pnNet.add(txtDepArea, "grow, wrap");
		txtDepArea.setText("500x500");
		pnNet.add(new JLabel("Sensing range (m): "));
		pnNet.add(txtSenRange, "grow, wrap");
		txtSenRange.setText("30");
		pnNet.add(new JLabel("Communication range (m): "));
		pnNet.add(txtCommRange, "grow, wrap");
		txtCommRange.setText("60");
		container.add(pnNet, "grow, wrap");
		
		container.add(btApply, "grow");
		btApply.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) { btApplyClick(evt); } });
	}
	
	public void applyChanges() {
		TString st = new TString(txtDepArea.getText(), 'x');
		double depW = Double.valueOf(st.getStrAt(0));
		double depH = Double.valueOf(st.getStrAt(1));
		network.setDepW(depW);
		network.setDepH(depH);
		TRadio.DF_RTX = Double.valueOf(txtCommRange.getText());
		TSenInf.DF_RSEN = Double.valueOf(txtSenRange.getText());
		TList net = network.getNetwork();
		for (int i=0; i<net.len(); i++) {
			TNode node = (TNode)net.get(i);
			node.getRadio().setTX(TRadio.DF_RTX);
			node.getSenInf().setRS(TSenInf.DF_RSEN);
		}
		network.getNetView().resizedResponse();
	}
	
	public void btApplyClick(ActionEvent evt) {
		applyChanges();
	}
}
